package cn.wolfcode.wolf2w.redis.service.impl;


import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService{
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {
        //key设置时必须满足redis原则，可读
        String key="verify_code:" + phone;
        //参数1：key 参数2：value参数3：有效时间  参数4：时间单位
        template.opsForValue().set(key, code, Consts.VERIFY_CODE_VAI_TIME * 60L, TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        String key=RedisKeys.VERIFY_CODE.join(phone);
        return template.opsForValue().get(key);
    }

    @Override
    public String setToken(UserInfo user) {
        //1:创建token(随机)
        String token=UUID.randomUUID().toString().replaceAll("-", "");
        String key=RedisKeys.USER_LOGIN.join(token);

        //2:设置redis
        //JSON格式字符串getTime()超时时间
        template.opsForValue().set(key, JSON.toJSONString(user), RedisKeys.USER_LOGIN.getTime(), TimeUnit.SECONDS);

        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key=RedisKeys.USER_LOGIN.join(token);
        if (template.hasKey(key)) {//hasKey存在时
            String userStr=template.opsForValue().get(key);
            /**
             * 反向操作parseObject将str转化为相应的JSONObject对象
             * 其中str是“键值对”形式的json字符串，转化为JSONObject对象之后就可以使用其内置的方法，进行各种处理
             */

            UserInfo userInfo=JSON.parseObject(userStr, UserInfo.class);
            //重置token有效时间延长
            template.expire(key, RedisKeys.USER_LOGIN.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }
        return null;
    }
}
